package service;

import java.sql.Types;
import java.util.List;
import java.util.UUID;

import model.User;

import dao.JdbcService;

public class UserService {
	
	private JdbcService jdbcService;
	
	public User getUserById(String userId) {
		String sql = "select * from user u where u.userid = ?";
		Object[] args = new Object[]{userId};
		List list = jdbcService.queryForList(sql, args, new User());
		User user = (User) list.get(0);
		return user;
	}
	
	public List getUsers() {
		String sql = "select * from user";
		Object[] args = new Object[]{};
		return jdbcService.queryForList(sql, args, new User());
	}
	
	public void createUser(String username) {
		String sql = "insert into user (userid,username) values(?,?)";
		Object[] args = new Object[]{UUID.randomUUID(),username};
		int[] argTypes = new int[] { Types.VARCHAR, Types.VARCHAR };
		jdbcService.update(sql, args, argTypes);
	}
	
	public void editUser(String username, String userId) {
		String sql = "update User u set username = ? where u.userid = ? ";
		Object[] args = new Object[] {username, userId};
		int[] argTypes = new int[] {Types.VARCHAR, Types.VARCHAR};
		jdbcService.update(sql, args, argTypes);
	}
	
	public void deleteUser(String userId) {
		String sql = "delete from user where userid = ? ";
		Object[] args = new Object[] {userId};
		int[] argTypes = new int[] {Types.VARCHAR};
		jdbcService.update(sql, args, argTypes);
	}
	//这个方法专门用来测试事务是否已经执行
	public void createUserTestTransaction(String username) {
		//先成功插入一个语句
		String sql = "insert into user (userid,username) values(?,?)";
		Object[] args = new Object[]{UUID.randomUUID(),username};
		int[] argTypes = new int[] { Types.VARCHAR, Types.VARCHAR };
		jdbcService.update(sql, args, argTypes);
		//故意写一条失败插入语句,注意多了一个?号
		sql = "insert into user (userid,username) values(?,?,?)";
		args = new Object[]{UUID.randomUUID(),username};
		argTypes = new int[] { Types.VARCHAR, Types.VARCHAR };
		jdbcService.update(sql, args, argTypes);
	}
	//去掉事务,具体配置可以设置read-only="true"实现,看是否第一个sql执行了！
	public void createUserTestWithoutTransaction(String username) {
		//先成功插入一个语句
		String sql = "insert into user (userid,username) values(?,?)";
		Object[] args = new Object[]{UUID.randomUUID(),username};
		int[] argTypes = new int[] { Types.VARCHAR, Types.VARCHAR };
		jdbcService.update(sql, args, argTypes);
		//故意写一条失败插入语句,注意多了一个?号
		sql = "insert into user (userid,username) values(?,?,?)";
		args = new Object[]{UUID.randomUUID(),username};
		argTypes = new int[] { Types.VARCHAR, Types.VARCHAR };
		jdbcService.update(sql, args, argTypes);
	}
	
	public void setJdbcService(JdbcService jdbcService) {
		this.jdbcService = jdbcService;
	}

	public JdbcService getJdbcService() {
		return jdbcService;
	}
}
